#include <stdio.h>
#include <stdlib.h>

#define MAX_SIEVE 1000000
#define NOT_PRIME (-1)

struct prime_str
{
	int number;
	unsigned long long value;
	/** 0 - not sent, 1 - sent. */
	char sent;
	/** 0 - not received, 1 - received and not a divisor, 2 - received and a divisor. */
	char received;
};

unsigned long long* sieve;
int i, j, n, k;

int main()
{
	printf("How many: ");
	scanf("%d", &n);
	printf("Finding primes, please wait\n");

	sieve = (unsigned long long*) malloc(sizeof(unsigned long long) * n);

	sieve[0] = 2;
	for (i = 1; i < n; i++)
		sieve[i] = 2 * i + 1;
	
	k = 0;
	for (i = 0; i < n; i++, k++)
	{
		if (k % 5000 == 0)
		{
			printf("i = %10d\n", i);
			k = 0;
		}
		if (sieve[i] == NOT_PRIME) continue;
		for (j = i+1; j < n; j++)
		{
			if ((sieve[j] % sieve[i]) == 0) sieve[j] = NOT_PRIME;
		}
	}

	FILE* file = fopen("primes", "wb");
	struct prime_str prime;
	j = 1;
	for (i = 0; i < n; i++)
	{
		if (sieve[i] == NOT_PRIME) continue;
		prime.number 	= j++;
		prime.value 	= sieve[i];
		prime.sent 		= 0;
		prime.received 	= 0;
		fwrite(&prime, sizeof(prime), 1, file);
	}
	fclose(file);
}
